package com.enjoy.xbase.db.impi;

import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.enjoy.xbase.db.handle.ISelectSql;
import com.enjoy.xbase.db.tools.DBTools;
import com.enjoy.xbase.db.tools.LogDb;
import java.util.ArrayList;
import java.util.List;

public class MSelectSql implements ISelectSql {
    private SQLiteDatabase db;
    private String sql;

    public MSelectSql(SQLiteDatabase db) {
        this.db = db;
    }

    @Override
    public ISelectSql selects(String sql) {
        this.sql = sql;
        return this;
    }

    @Override
    public <T> List<T> finds(Class<T> modelClass) {
        if (this.db == null) {
            return null;
        }
        Cursor cursor = db.rawQuery(sql, null);
        List<T> datas = new ArrayList<>();
        if (cursor.moveToFirst()) {
            do {
                try {
                    datas.add((T) DBTools.cursor2Obj(cursor, modelClass));
                } catch (Exception e) {
                    LogDb.err("数据库异常", "添加异常" + e.toString());
                }
            } while (cursor.moveToNext());
        }
        cursor.close();
        return datas;
    }

    @Override
    public <T> T find(Class<T> modelClass) {
        List<T> datas = finds(modelClass);
        if (datas != null && datas.size() > 1) {
            throw new RuntimeException("查询结果数量大于1");
        } else if (datas != null && datas.size() == 1) {
            return datas.get(0);
        } else {
            return null;
        }
    }
}
